package com.wondertek.poms.service.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IChannelInfoPackageService;
import com.wondertek.poms.core.service.IChannelPackageService;
import com.wondertek.poms.dao.po.ChannelInfoPackage;
import com.wondertek.poms.dao.po.ChannelPackage;
import com.wondertek.poms.dao.pojo.ChannelPackagePojo;
import com.wondertek.poms.service.message.SendAbility;
import com.wondertek.poms.service.vo.ChannelPackageEditVo;
import com.wondertek.poms.service.vo.ChannelPackageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping(value = "/channel-package")
@Slf4j
public class ChannelPackageController {

	@Autowired
	private IChannelPackageService channelPackageService;
	@Autowired
	private IChannelInfoPackageService channelInfoPackageService;
	@Autowired
	private SendAbility sendAbility;

	@GetMapping(value = "/list")
	@ResponseBody
	public ResultBean list(ChannelPackageVo channelPackageVo,
	                       @RequestParam(defaultValue = "1") int page,
	                       @RequestParam(defaultValue = "20") int rows,
	                       @RequestParam(defaultValue = "CREATE_TIME") String sidx,
	                       @RequestParam(defaultValue = "desc") String sord) {
		ChannelPackagePojo channelPackagePojo = new ChannelPackagePojo();
		BeanUtils.copyProperties(channelPackageVo, channelPackagePojo);
		Page<ChannelPackage> list = channelPackageService.findAll(channelPackagePojo, page, rows, sord, sidx);
		return PageBean.ok(list.getTotalPages(), list.getTotalElements(), list.getContent());
	}

	@GetMapping(value = "/list-for-select")
	@ResponseBody
	public ResultBean list() {
		return PageBean.ok(channelPackageService.findForSelect());
	}

	@PostMapping(value = "/add")
	@ResponseBody
	@MethodLog(module = "产品组新增",insertDB=true)
	public ResultBean add(@RequestBody ChannelPackageVo channelPackageVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(channelPackageVo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		if (isRepeat(channelPackageVo)) {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}

		ChannelPackage channelPackage = new ChannelPackage();
		BeanUtils.copyProperties(channelPackageVo, channelPackage);
		ChannelPackage.putTimeAndUser(channelPackage);
		channelPackage.setIsPublish(0);
		channelPackage = channelPackageService.save(channelPackage);
		HashSet<String> set = new HashSet<>();
		Integer errNum = checkChannelIds(channelPackageVo.getChannelId(), set);
		if (errNum > 0) {
			channelPackageService.deleteById(channelPackage.getId());
			return ResultBean.error("新增失败：渠道id格式不正确");
		}
		channelInfoPackageService.saveChannelInfo(set, channelPackage.getId());
		return ResultBean.ok();
	}

	public Integer checkChannelIds(String channels, HashSet<String> set) {
		Integer errNum = 0;
		for (String temp : channels.split(",|，")) {
			if (temp.length() != 15) {
				errNum++;
			} else {
				set.add(temp);
			}
		}
		return errNum;
	}


	@GetMapping(value = "/get")
	@ResponseBody
	public ResultBean get(String packageId) {
		if (StrUtil.isBlank(packageId)) {
			return ResultBean.error("渠道id不能为空！");
		}
		ChannelPackagePojo channelPackagePojo = new ChannelPackagePojo();
		ChannelPackage channelPackage = channelPackageService.get(Convert.toLong(packageId));
		BeanUtils.copyProperties(channelPackage, channelPackagePojo);
		List<ChannelInfoPackage> list = channelInfoPackageService.findAllByPackageId(Convert.toLong(packageId));
		List<String> channels = new ArrayList<>();
		if (list != null && list.size() > 0) {
			for (ChannelInfoPackage channelInfoPackage : list) {
				channels.add(channelInfoPackage.getChannelId());
			}
		}
		channelPackagePojo.setChannelIdList(channels);
		return ResultBean.ok(channelPackagePojo);
	}

	@PutMapping(value = "/edit")
	@ResponseBody
	@MethodLog(module = "产品组编辑",insertDB=true,opterate = 2)
	public ResultBean edit(@RequestBody ChannelPackageEditVo channelPackageEditVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(channelPackageEditVo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		ChannelPackage channelPackage = channelPackageService.findById(channelPackageEditVo.getId());
		if (channelPackage != null) {
			/*if (channelPackage.getIsPublish() == 1) {
				return ResultBean.error("该渠道包已发布，不能编辑！");
			}*/
			ChannelPackageVo channelPackageVo=new ChannelPackageVo();
			channelPackageVo.setName(channelPackageEditVo.getName());
			if (!channelPackage.getName().equals(channelPackageVo.getName())) {
				if (isRepeat(channelPackageVo)) {
					return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
				}
			}

			channelPackage.setName(channelPackageEditVo.getName());
			channelPackage.setProperty(channelPackageEditVo.getProperty());
			channelPackage.setDetail(channelPackageEditVo.getDetail() != null ? channelPackageEditVo.getDetail() : null);
			channelPackage.setIsPublish(0);
			ChannelPackage.putTimeAndUser(channelPackage);
			channelPackageService.save(channelPackage);
		}
		return ResultBean.ok();
	}

	@DeleteMapping(value = "/delete")
	@ResponseBody
	@MethodLog(module = "产品组删除",insertDB=true,opterate = 3)
	public ResultBean delete(String ids) {
		if (StrUtil.isBlank(ids)) {
			return ResultBean.error("渠道id不能为空！");
		}
		StringBuffer msg = new StringBuffer();
		StringBuffer errMessage = new StringBuffer();
		AtomicInteger errorNum = new AtomicInteger();//错误数
		AtomicInteger successNum = new AtomicInteger();//成功数
		String[] idArray = ids.split(",|，");
		for (String id : idArray) {
			if (checkDate(id, errMessage, errorNum)) {
				channelPackageService.deleteByPackageId(Convert.toLong(id));
				successNum.addAndGet(1);
			}
		}
		if (errorNum.get() > 0) {
			msg.append("已发布的渠道包，不能删除！");
			return ResultBean.error(msg.toString());
		}
		return ResultBean.ok(msg.toString());
	}

	@GetMapping(value = "/add-channel")
	@ResponseBody
	@MethodLog(module = "产品组添加渠道",insertDB=true)
	public ResultBean addChannel(String packageId, String channelIds) {
		if (StrUtil.isBlank(channelIds)) {
			return ResultBean.error("渠道id不能为空！");
		}
		if(StrUtil.isBlank(packageId)){
			return ResultBean.error("渠道包id不能为空！");
		}
		HashSet<String> set = new HashSet<>();
		Integer errNum = checkChannelIds(channelIds, set);
		if (errNum > 0) {
			return ResultBean.error("新增失败：渠道id格式不正确");
		}
		channelInfoPackageService.saveChannelInfo(set, Convert.toLong(packageId));
		return ResultBean.ok();
	}

	@DeleteMapping(value = "/del-channel")
	@ResponseBody
	@MethodLog(module = "产品组删除渠道",insertDB=true,opterate = 3)
	public ResultBean delChannel(String packageId, String channelIds) {
		if (StrUtil.isBlank(channelIds)) {
			return ResultBean.error("渠道id不能为空！");
		}
		if(StrUtil.isBlank(packageId)){
			return ResultBean.error("渠道包id不能为空！");
		}
		channelInfoPackageService.deleteChannelInfo(channelIds, Convert.toLong(packageId));
		return ResultBean.ok();
	}

	@GetMapping(value = "/get-channels")
	@ResponseBody
	public ResultBean getChannels(String packageId) {
		if (StrUtil.isBlank(packageId)) {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980203));
		}
		List<ChannelInfoPackage> list = channelInfoPackageService.findAllByPackageId(Convert.toLong(packageId));
		List<String> channels = new ArrayList<>();
		if (list != null && list.size() > 0) {
			for (ChannelInfoPackage channelInfoPackage : list) {
				channels.add(channelInfoPackage.getChannelId());
			}
		}
		return ResultBean.ok(channels);
	}

	@GetMapping(value = "/get-channel-package-names")
	@ResponseBody
	public ResultBean getChannelPackages() {
		List<String> list = channelPackageService.getAllPackageNames();
		return ResultBean.ok(list);
	}

	public Boolean checkDate(String id, StringBuffer errMessage, AtomicInteger errorNum) {
		Boolean flag = true;
		ChannelPackage channelPackage = channelPackageService.findById(Convert.toLong(id));
		if (channelPackage.getIsPublish() == 1) {
			errorNum.addAndGet(1);
			flag = false;
			errMessage.append("已发布的渠道包，不能删除！.  ");
		}
		return flag;
	}

	/**
	 * 用于下拉
	 *
	 * @return 所有已发布的渠道包
	 */
	@GetMapping("/get-all")
	public ResultBean getAll() {
		List<ChannelPackage> list = channelPackageService.findAllByIsPublish();
		return ResultBean.ok(list);
	}


	@GetMapping(value = "/online")
	@ResponseBody
	@MethodLog(module = "产品组发布",insertDB=true,opterate = 4)
	public ResultBean online(String packageIds){
		if(StrUtil.isBlank(packageIds)){
			return ResultBean.error(MessageCodes.get(MessageCodes.M980203));
		}
		String[] idArray = packageIds.split(",|，");
		for(String packageId : idArray){
			ChannelPackage channelPackage=channelPackageService.get(Convert.toLong(packageId));
			channelPackage.setIsPublish(1);
			ChannelPackage.putTimeAndUser(channelPackage);
			channelPackageService.save(channelPackage);
		}

		Boolean flag = publishGroup(idArray,0);
		if(!flag){
			return ResultBean.error("发布失败");
		}
		return ResultBean.ok();
	}

	@GetMapping(value = "/offline")
	@ResponseBody
	@MethodLog(module = "产品组撤回",insertDB=true,opterate = 5)
	public ResultBean offline(String packageIds){
		if(StrUtil.isBlank(packageIds)){
			return ResultBean.error(MessageCodes.get(MessageCodes.M980203));
		}
		String[] idArray = packageIds.split(",|，");
		for(String packageId : idArray){
			ChannelPackage channelPackage=channelPackageService.get(Convert.toLong(packageId));
			channelPackage.setIsPublish(0);
			ChannelPackage.putTimeAndUser(channelPackage);
			channelPackageService.save(channelPackage);
		}
		Boolean flag = publishGroup(idArray,1);
		if(!flag){
			return ResultBean.error("撤回失败");
		}
		return ResultBean.ok();
	}

	public Boolean publishGroup(String[] idArray,Integer oprCode){
		String type="4";
		log.info("开始发送能力平台流程");
		Boolean flag = sendAbility.sendToAbility(0L,1,"channelPkgs",type);
		log.info("发送能力平台流程结束，结果："+flag);
		if(!flag){
			for(String packageId : idArray){
				ChannelPackage channelPackage=channelPackageService.get(Convert.toLong(packageId));
				channelPackage.setIsPublish(oprCode);
				ChannelPackage.putTimeAndUser(channelPackage);
				channelPackageService.save(channelPackage);
			}
		 }
		return flag;
	}

	public Boolean isRepeat(ChannelPackageVo channelPackageVo) {
		ChannelPackage temp = new ChannelPackage();
		temp.setName(channelPackageVo.getName());
		Optional<ChannelPackage> opt = channelPackageService.findOne(Example.of(temp));
		if (opt.isPresent()) {
			ChannelPackage channelPackage = opt.get();
			if (channelPackageVo.getId() != null && channelPackage.getId() != channelPackageVo.getId()) {
				return true;
			}
			if (channelPackageVo.getId() == null) {
				return true;
			}
		}
		return false;
	}
}
